home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: How do I round and truncate floats to integers?
- Date: Thu, 22 Feb 96 01:02:13 GMT
- Organization: none
- Message-ID: <824950933snz@genesis.demon.co.uk>
- References: <4g009b$c2n@news.tuwien.ac.at> <harmon.824447677@pegasus.montclair.edu> <Dn4oM5.1JK@uns.bris.ac.uk>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <Dn4oM5.1JK@uns.bris.ac.uk>
- nathan@pact.srf.ac.uk "Nathan Sidwell" writes:
-
- >Now it just so happens that when the result of casting a signed int to an
- >unsigned int is not implementation defined (ie the value to
- >be converted is representable in both types), there is no change
- >to the bit pattern, for a common representation of binary integers (twos
- >complement).
-
- If the value is representable in both types it is a non-negative value. From
- 6.1.2.5
-
- "The range of nonnegative values of a signed integer is a subrange of the
- corresponding unsigned integer type, and the representation of the same
- value in each case is the same"
-
- So what you say above is true for any legal representation, not just 2's
- complement.
-
- The only thing that is implementation defined about converting a signed
- int to an unsigned int is the value of UINT_MAX.
-
- >Many compilers extend the conversion in an implementation
- >defined manner, so that there is never a change in the bit pattern.
-
- This is the consequence of using 2's complement representation.
-
- >This may be where your confusion is coming from.
-
- Simply remember that the effects of a cast are defined on an object's type
- and value, *not* its representation. For example the result of converting
- (either implicitly or by using a cast) a floating point value to an
- integer value is to truncate the value to the nearest integer that is smaller
- in magnitude (i.e. discard the fractional part). If the resulting value
- can't be represented in the target type the behaviour is undefined. This
- can clearly result in a complete change in the bit pattern involved, even
- in the number of bits in the value.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-